/**
 * Copyright 2014 wasu.com
 *
 *
 * Create on 2015年10月21日 下午4:36:24
 */
package xj.toolkit.rpc.core;

import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import xj.toolkit.netty.handler.codec.http.reactor.HttpReactor;
import xj.toolkit.netty.handler.codec.http.request.HttpRequestExt;
import xj.toolkit.rpc.assemble.RpcServiceDescriptor;
import xj.toolkit.rpc.assemble.RpcServiceManager;

/**
 * @author <a href="mailto:caoxiaojian@wasu.cn">xiaojiancao</a>
 *
 */
@Service("hessianReactor")
public class HessianInvocationReactor implements HttpReactor {

	private static final Logger logger = LoggerFactory.getLogger(HessianInvocationReactor.class);

	@Autowired
	private RpcServiceManager rpcServiceManager = null;

	@Autowired
	private RpcServiceInvocationerHandler rpcServiceInvocationerHandler = null;

	@Override
	public void onHttpRequest(FullHttpRequest request) {
		String uri = request.getUri();
//		if (!uri.startsWith("/apis/")) {
//			sendResourceNotFound(request);
//			return;
//		}
		if (uri.endsWith("/")) {
			uri = uri.substring(0, uri.length() - 1);
		}

		String serviceName = uri.substring(uri.lastIndexOf("/") + 1);

		RpcServiceDescriptor rpcServiceDescriptor = rpcServiceManager.getRpcServiceByName(serviceName);

		if (rpcServiceDescriptor == null) {
			logger.error("Cannot found service[{}].", serviceName);
			sendServiceNotFound(request);
		}

		try {
			rpcServiceInvocationerHandler.invoke(rpcServiceDescriptor, (HttpRequestExt)request);
		} catch (Exception exception) {
			logger.error("Invoke fail, service[" + rpcServiceDescriptor + "]", exception);
			sendServerError(request);
		}
	}

	private void sendServiceNotFound(FullHttpRequest request) {
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
		response.content().writeBytes("Service NOT FOUND.".getBytes());
		response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
		SendHepler.sendResponse((HttpRequestExt) request, response);
	}

//	private void sendResourceNotFound(FullHttpRequest request) {
//		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
//		response.content().writeBytes("Resource NOT FOUND.".getBytes());
//		response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
//		SendHepler.sendResponse((HttpRequestExt) request, response);
//	}

	private void sendServerError(FullHttpRequest request) {
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
				HttpResponseStatus.INTERNAL_SERVER_ERROR);
		response.content().writeBytes("INTERNAL_SERVER_ERROR.".getBytes());
		response.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
		SendHepler.sendResponse((HttpRequestExt) request, response);
	}

}
